# -*- coding: utf-8 -*-
# @author: HRUN
"""
简化的Django初始化模块
"""

import os
import sys

# 全局变量
_django_initialized = False
_models_cache = None

def setup_django():
    """设置Django环境"""
    global _django_initialized
    
    if _django_initialized:
        return True
    
    try:
        # 设置环境变量 - 在导入任何模块之前设置
        os.environ['GEVENT_SUPPORT'] = 'False'
        os.environ['GEVENT_MONKEY_PATCH'] = 'False'
        
        # 禁用gevent的monkey patching警告
        import warnings
        warnings.filterwarnings("ignore", category=UserWarning, module="gevent.monkey")
        warnings.filterwarnings("ignore", category=UserWarning, module="locust")
        
        # 添加项目路径 - 更健壮的路径处理
        current_dir = os.path.dirname(os.path.abspath(__file__))
        backend_dir = os.path.dirname(current_dir)
        
        # 确保路径存在且添加到sys.path
        if backend_dir not in sys.path:
            sys.path.insert(0, backend_dir)
            print(f"已添加backend路径: {backend_dir}")
        
        # 检查Django设置模块是否已设置
        # 统一通过ENV变量判断
        if "DJANGO_SETTINGS_MODULE" not in os.environ:
            env = os.environ.get("ENV")
            if env == "production":
                settings_module = "primaryApp.settings.pro"
            else:
                settings_module = "primaryApp.settings.dev"
            os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)

        
        # 初始化Django
        import django
        django.setup()
        
        # 确保数据库连接池配置正确
        from django.db import connection
        from django.db import close_old_connections
        
        # 关闭旧的数据库连接
        close_old_connections()
        
        _django_initialized = True
        return True
        
    except Exception as e:
        print(f"Django初始化失败: {e}")
        print(f"当前工作目录: {os.getcwd()}")
        print(f"Python路径: {sys.path[:5]}...")  # 只显示前5个路径
        print(f"环境变量DJANGO_SETTINGS_MODULE: {os.environ.get('DJANGO_SETTINGS_MODULE', '未设置')}")
        return False

def get_models():
    """获取Django模型"""
    global _models_cache
    
    if _models_cache is not None:
        return _models_cache
    
    if not _django_initialized:
        if not setup_django():
            raise RuntimeError("无法初始化Django")
    
    try:
        # 确保数据库连接正确
        from django.db import close_old_connections
        close_old_connections()
        
        from performance.models import PerformanceTask, TaskReport, PerformanceTestLog, server
        from projects.models import TestEnv
        
        _models_cache = {
            'PerformanceTask': PerformanceTask,
            'TaskReport': TaskReport,
            'PerformanceTestLog': PerformanceTestLog,
            'TestEnv': TestEnv,
            'server': server
        }
        return _models_cache
        
    except Exception as e:
        print(f"获取模型失败: {e}")
        raise 